from flask import Flask,request,render_template,redirect,session
import config
from decorators import *
from config import *
from KnowledgeGraph.Interpreter import Interpreter
from KnowledgeGraph.CsynToId import transFuncMap
import re
app = Flask(__name__)
app.config.from_object(config)
@app.route('/',methods=['GET','POST'])
def mainpage():
    #主页
    if request.method=='POST':
        #collname为集合名字
        collection=db.views
        #获取前端的关键字
        keyWord1 = request.form.get("s1")
        #根据名字搜索数据库
        filter = {}
        keyword = keyWord1
        condition = {}
        condition['$regex'] = keyword
        filter["Name"] = condition
        res = db.views.find(filter)
        content = {
            'views':res
        }

        if res.count() == 0:
            alter = "1"
            return render_template('index.html', **content, alter=alter)
        else:
            return render_template('index.html', **content)
    else:

        db.views.find()
        #所有景点数据渲染到主页
        content={
             'views':db.views.find()
        }
    return render_template('index.html',**content)
#登录
# @app.route('/',methods=['GET','POST'])
# def Login():
#     #登陆验证
#     if request.method=='POST':
#         #获取用户名密码
#         username=request.form.get("username")
#         userpass=request.form.get("userpass")
#         client=MongoClient()
#         #用户数据库名
#         db=client.user
#         #用户数据库集合名
#         collection=db.users
#         data=collection.find({"username":username,"userpass":userpass})
#         i=0
#         for d in data:
#             i=i+1
#         if i>0:
#             #登陆成功跳转到主页
#             return redirect("/helloworld")
#         else:return render_template("aas.html")
#     #ass是一个简单的登陆页面，在templates里面
#     return render_template('aas.html')
@app.route('/personinfor/',methods=['GET','POST'])
def personinfor():
    #获取用户上传的个人信息
    #智能推荐界面
    #调用KnowledgeGraph
    if request.method == 'POST':
            shouji=request.form.get("shouji")
            zhiye=request.values.get("zhiye")
            nianling = request.values.get("nianling")
            leixing = request.values.get("leixing")
            if zhiye=='未选择'or nianling=='未选择' or leixing=='未选择':
                alert=2
                return render_template('personinfor.html',alert=alert)
            nianling=request.values.get("nianling")
            leixing=request.values.get("leixing")
            session['shouji']=shouji
            Inter=Interpreter('DBNAME', transFuncMap=transFuncMap)
            seq1=[str(zhiye)+'.喜欢的景点类型']
            seq2=[str(nianling)+'.年龄人群']
            seq3=[str(leixing)+'.类别人群']
            list1=Inter.run(seq1)
            list2=Inter.run(seq2)
            list3=Inter.run(seq3)
            #list1是景点类型，list2和list3是适宜人群
            views=[]
            views1=[]
            views2=[]
            for l in list1:
               type=str(l[0])
               seq=[type+'.景点类型逆']
               list_views=Inter.run(seq)
               for view in list_views:
                   views.append(view[0])
            for l in list2:
                person = str(l[0])
                seq = [person + '.景点人群逆']
                list_views = Inter.run(seq)
                for view in list_views:
                    views1.append(view[0])
            for l in list3:
                person = str(l[0])
                seq = [person + '.景点人群逆']
                list_views = Inter.run(seq)
                for view in list_views:
                    views2.append(view[0])
            tmp0 = [val for val in views if val in views1]
            tmps=[val for val in views2 if val in tmp0]
            session['tmps']=tmps
            monlist=[]
            for t in tmps:
                s=[t+'普通票.普通票价格']
                mon=Inter.run(s)
                if mon:
                    mon=mon[0][0]
                    mon=str(mon)
                    if mon=='免费':
                        mon='0'
                    else:
                        mon=re.compile('(\d+)').search(mon).group(1)
                    monlist.append(int(mon))
            view_money=0
            i=0
            k=0
            views_monlist=[]
            for m in range(len(monlist)):
                view_money=view_money+monlist[m]
                i=i+1
                if(i==5):
                    views_monlist.append(view_money)
                    view_money=0
                    i=0
                    k=k+1
                    continue
                if k == 15:
                    break
            session['money']=views_monlist
            a=''
            b=[]
            i=0
            k=0
            for j in range(len(tmps)):
                a=a+tmps[j]+'>'
                i=i+1
                if(i==5):
                    b.append(a+'结束')
                    a=''
                    i=0
                    k=k+1
                    continue
                if k == 15:
                    break
            num=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
            session['infor']=b
            session['num']=num
            return redirect(url_for('luxian'))
    else:
        return render_template('personinfor.html')

@app.route('/Recommend/',methods=['GET','POST'])
@infor_required
def Recommend():
    if request.method == 'POST':
        type = request.values.getlist('type')
        time=request.values.get('time')
        if type==None or time==None:
            alert=1
            return render_template('Recommend.html',alert=alert)
        views=[]
        for ty in type:
            seq=[str(ty)+'.景点类型逆']
            Inter = Interpreter('DBNAME', transFuncMap=transFuncMap)
            view=Inter.run(seq)
            for v in view:
                views.append(v[0])
        views = list(set(views))
        views2=session.get('tmps')
        views3 = [val for val in views if val in views2]
        monlist=[]
        for t in views3:
            s = [t + '普通票.普通票价格']
            mon = Inter.run(s)
            if mon:
                mon = mon[0][0]
                mon = str(mon)
                if mon == '免费':
                    mon = '0'
                else:
                    mon = re.compile('(\d+)').search(mon).group(1)
                monlist.append(int(mon))
        view_money = 0
        i = 0
        k = 0
        views_monlist = []
        for m in range(len(monlist)):
            view_money = view_money + monlist[m]
            i = i + 1
            if (i == int(time)):
                views_monlist.append(view_money)
                view_money = 0
                i = 0
                k = k + 1
                continue
            if k == 15:
                break
        session['j_money']=views_monlist
        a = ''
        c = []
        i = 0
        k=0
        for j in range(len(views3)):
            a = a + views3[j] + '>'
            i = i + 1
            if (i == int(time)):
                c.append(a + '结束')
                a = ''
                i = 0
                k=k+1
                continue
            if k==6:
                break
        session['j_infor']=c

        return redirect(url_for('luxian'))
    else:
       return render_template('Recommend.html')

@app.route('/Wish_list/',methods=['GET','POST'])
@infor_required
def Wish_list():
    #心愿清单界面
    if request.method == 'POST':
        dict = request.args['view_name']
        print(dict)
    else:
         return render_template('Wish_list.html')

@app.route('/luxian/',methods=['GET','POST'])
@infor_required
def luxian():
    #我的路线界面
    if request.method == 'POST':
        return render_template('luxian.html')
    else:
      if session.get('j_infor'):
          j_infor=session.get('j_infor')
          money = session.get('money')
          infor = session.get('infor')
          j_money=session.get('j_money')
          num=session.get('num')
          content=zip(infor,num,money)
          content2=zip(j_infor,num,j_money)
          return render_template('luxian.html',content=content,content2=content2)
      infor=session.get('infor')
      money = session.get('money')
      num = session.get('num')
      content= zip(infor,num,money)
      return render_template('luxian.html',content=content)

@app.route('/contact/',methods=['GET','POST'])
@infor_required
def contact():
    #电子导游界面
    if request.method == 'GET':
        infor=session.get('infor')
        num=session.get('num')
        content=zip(infor,num)
        return render_template('contact.html',content=content)

    else:
        infor = session.get('infor')
        num = session.get('num')
        content = zip(infor, num)
        luxian= request.values.get("luxian")
        luxian=luxian.split('>')
        luxian=luxian[:-1]
        luxian1=luxian[:-1]
        luxian2=luxian[-(len(luxian)-1):]
        content2=zip(luxian1,luxian2,num)
        content3=zip(luxian1,luxian2,num)
        return render_template('contact.html',content=content,content2=content2,content3=content3)
@app.route('/contact_j/',methods=['GET','POST'])
@infor_required
def contact_j():
    #电子导游界面
    if request.method == 'GET':
        infor=session.get('j_infor')
        num=session.get('num')
        content=zip(infor,num)
        return render_template('contact_j.html',content=content)

    else:
        infor = session.get('j_infor')
        num = session.get('num')
        content = zip(infor, num)
        luxian= request.values.get("luxian")
        luxian=luxian.split('>')
        luxian=luxian[:-1]
        luxian1=luxian[:-1]
        luxian2=luxian[-(len(luxian)-1):]
        content2=zip(luxian1,luxian2,num)
        content3=zip(luxian1,luxian2,num)
        return render_template('contact_j.html',content=content,content2=content2,content3=content3)

if __name__ == '__main__':
    app.run(debug=True)
